package com.adong.springboot.config;

import com.adong.springboot.filter.MyFilter;
import com.adong.springboot.listener.MyListener;
import com.adong.springboot.servlet.MyServlet;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * 关于Servlet的相关配置
 * Web项目中三大组件(Servlet,Listener,Filter)是通过web.xml里面配置的
 * 而Springboot没有xml文件
 */
@Configuration
public class MyServletConfig {

    /**
     * 定制嵌入式Servlet容器
     *
     * @return
     */
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            //定制嵌入式Servlet的相关规则
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                //设置端口
                factory.setPort(8081);
            }
        };
    }

    /**
     * 定制三大组件
     * http://localhost:8081/myServlet 访问成功
     */


    //注册Servlet组件
    @Bean
    public ServletRegistrationBean myServlet() {
        ServletRegistrationBean<MyServlet> myServlet = new ServletRegistrationBean<>(new MyServlet(), "/myServlet");
        return myServlet;
    }

    //注册Filter组件
    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean<MyFilter> myFilter = new FilterRegistrationBean<MyFilter>();
        myFilter.setFilter(new MyFilter());
        myFilter.setUrlPatterns(Arrays.asList("/myServlet"));
        return myFilter;
    }

    //注册Listener组件
    @Bean
    public ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean() {
        ServletListenerRegistrationBean<MyListener> listenerRegistrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return listenerRegistrationBean;
    }

}
